package com.rzjm.api.pay.utils;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpPostUtil {

	public String exec(String urlPath, String data) {
		try {
			// 把XML的数据转成字符串
			byte[] bb = data.getBytes("UTF-8");
			// 请求地址
			URL url = new URL(urlPath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(5 * 1000);// 设置超时的时间
			conn.setDoInput(true);
			conn.setDoOutput(true);// 如果通过post提交数据，必须设置允许对外输出数据
			conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
			conn.setRequestProperty("Content-Length", String.valueOf(bb.length));
			conn.connect();
			DataOutputStream out = new DataOutputStream(conn.getOutputStream());
			out.write(bb);// 写入请求的字符串
			out.flush();
			out.close();
			// 请求返回的状态
			if (conn.getResponseCode() == 200) {
				System.out.println("http response yes");
				// 请求返回的数据
				InputStream in = conn.getInputStream();
				String a = null;
				try {
					byte[] data1 = new byte[in.available()];
					in.read(data1);
					// 转成字符串
					a = new String(data1,"UTF-8");
					return a;
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			} else {
				System.out.println("http response no");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
}
